// pages/index/index.tsx
import React, {useEffect, useState} from 'react'
import {View, Text} from '@tarojs/components'
import HeaderTitle from "@/components/HeaderTitle";
import {defaultUser, UserModel, UserType} from "@/shared/services/model/user";
import {Image} from '@nutui/nutui-react-taro'
import './index.scss'
import QRCode from 'qrcode'
import Taro from '@tarojs/taro'

const Index: React.FC = () => {
  const [user, setUser] = useState<UserModel>(defaultUser)

  const [qrCodeUrl, setQrCodeUrl] = useState('')

  const generateQRCode = async (text) => {
    try {
      const url = await QRCode.toDataURL(text, {
        width: 200,
        margin: 2,
        color: {
          dark: '#000000',
          light: '#FFFFFF'
        }
      })
      setQrCodeUrl(url)
    } catch (err) {
      console.error('生成二维码失败:', err)
    }
  }

  // 保存二维码到相册
  const saveQRCode = () => {
    if (!qrCodeUrl) return

    Taro.saveImageToPhotosAlbum({
      filePath: qrCodeUrl,
      success: () => {
        Taro.showToast({
          title: '保存成功',
          icon: 'success'
        })
      },
      fail: (err) => {
        console.error('保存失败:', err)
        Taro.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    })
  }

  useEffect(() => {
    generateQRCode(`user:${user.id}`)
  }, [])

  return (
    <View className='pageContainer'>
      <HeaderTitle title={'我的二维码'} />

      {/* 用户信息 */}
      <View className="userInfo">
        <Text className="userName">{user.name}</Text>
        <Text className="userLocation">上海 浦东新区</Text>
      </View>

      {/* 二维码区域 */}
      <View className="qrCodeArea">
        <View className="qrCodeBox">
          {qrCodeUrl && (
            <Image
              className="qrCodeImage"
              src={qrCodeUrl}
              mode="widthFix"
            />
          )}
        </View>

        <Text className="qrTip">
          扫一扫上面的二维码图案，加载为朋友。
        </Text>
      </View>

      {/* 操作按钮 */}
      <View className="actionBar">
        <View className="actionItem">
          <Text className="actionIcon">📷</Text>
          <Text className="actionText">扫一扫</Text>
        </View>

        <View className="actionItem">
          <Text className="actionIcon">🔄</Text>
          <Text className="actionText">换个样式</Text>
        </View>

        <View className="actionItem" onClick={saveQRCode}>
          <Text className="actionIcon">💾</Text>
          <Text className="actionText">保存图片</Text>
        </View>
      </View>
    </View>
  )
}

export default Index
